import {
  Button,
  ConfigProvider,
  Dialog,
  Input,
  Loading,
  Toast,
} from "@nutui/nutui-react-taro";
import { ArrowRight, Close, Ask } from "@nutui/icons-react-taro";
import { Form } from "@nutui/nutui-react-taro";

import Taro, { useShareAppMessage } from "@tarojs/taro";
import { View } from "@tarojs/components";


import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  carList,
  changeCarList,
  changeUser,
  phoneOpenid,
  storeUser,
} from "@/redux/userSlice";

import {
  ApiCheckLogin,
  ApiLogout,
  ApiMemberCarAdd,
  ApiMemberCarList,
  ApiMemberCarUpdate,
} from "../../utils/api";

import "./index.scss";

import dayjs from "dayjs";
import Keyboard from "./keyboard/index";


const member = () => {
  useShareAppMessage((res) => {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }

    return {
      title: "东进会员",
      path: "pages/home/index", //?id=123
      // imageUrl,
      imageUrl: "../../assets/home.jpg",
    };
  });
  // 表单控件
  const [form] = Form.useForm();

  // 导入仓库 2.使用属性
  const dispatch = useDispatch();
  // const storeMemberId = useSelector(storeMember_id);
  const user = useSelector(storeUser);
  const myOpenid = useSelector(phoneOpenid);
  const memberCarList = useSelector(carList);

  const [state, SetState] = useState({
    msg: "toast",
    type: "text",
    cover: false,
    duration: 2,
    closeOnOverlayClick: false,
    icon: "",
    center: true,
  });
  const [showToast, SetShowToast] = useState(false);
  const openToast = (
    type: string,
    msg: string,
    duration?: number,
    icon?: string
  ) => {
    const changeState = Object.assign(state, {
      type,
      msg,
      duration,
      icon,
    });
    SetState(changeState);
  };

  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);

  // 输入车牌号
  const [memberVal, setMemberVal] = useState("");
  const [createTime, setCreateTime] = useState("");
  const [updateTime, setUpdateTime] = useState("");
  // 新会员车辆
  const [member, setMember] = useState<Datum[]>([
    {
      plate_number: "",
    },
  ]);
  const [currentInput, setCurrentInput] = useState(0); //
  const [newEnergy, setNewEnergy] = useState(false); //
  // const [member, setMember] = useState<Datum>({});
  // 骨架屏
  const [loading, setLoading] = useState(true);

  const [showKeyboard, setShowKeyboard] = useState(true); //
  const [isInput, setIsInput] = useState(false);

  // 提示
  const [visibleTip, setVisibleTip] = useState(false);

  const [tipTxt,setTipTxt] = useState(false)
  // 请求登录状态
  const checkLogin = async () => {
    if (!myOpenid) {
      // 去到注册页
      Taro.removeStorageSync("encryptedUserToken");
      // navigate("/register");
      Taro.reLaunch({
        url: "/pages/home/index",
      });
    }
    console.log(myOpenid, "openid");
    // console.log(formData, "formData");
    // 暂时先用手机号+
    const res = await ApiCheckLogin(myOpenid);
    if (res.code == 0) {
      //  存到仓库？
      // console.log(res.data.member_id, "member_id");
      // 当前页面使用
      setMember_id(res.data.member_id);
      // await getMemberInfo(res.data.member_id);
      // 用于后续 获取会员详情信息
      console.log(res.data.member_id);
      // await getMemberInfo(res.data.member_id);
      return res.data.member_id;
    } else if (res.code == 2001) {
      await ApiLogout();
      await checkLogin();
    } else {
      console.log("未登录");
      return;
    }
  };

  const [isTxt, setIsTxt] = useState(true);
  // 输入车牌号 或修改车牌号
  const changeMember = async (val) => {
    // 创建新的 member ，更新 plate_number
    const newMember = [{ ...member[0], plate_number: val }];
    // 更新 member 状态
    setMember(newMember);
    // console.log(val, "val");
  };

  // 跳转主页
  const determine = async () => {
    //
    if (!member[0].plate_number) {
      // Toast.show("请输入新车牌号");
      Toast.show("test", {
        title: "请输入新车牌号",
        duration: 2,
      });
      return;
    }

    if (member[0].plate_number == memberVal) {
      Taro.redirectTo({
        url: "/pages/home/index",
      });
      // Toast.show("车牌号一致");
      // Toast.show("test", {
      //   title: "车牌号一致",
      //   duration: 2,
      // });
      Taro.showToast({
        title: "车牌号一致",
        icon: "error",
        duration: 2000,
      });
      return;
    }

    // 校验
    let plate_number = member[0].plate_number;
    const keyboardVal = plate_number.slice(0, 7).replace(/-/g, "");
    if (keyboardVal.length < 7) {
      Taro.showToast({
        title: "车牌号有误",
        icon: "error",
        duration: 2000,
      });
      setMember([
        {
          ...member[0],
          plate_number: "",
        },
      ]);
      // 初始化索引
      setIsTxt(true);
      return;
    }
    if (plate_number[7] && plate_number[7] == "-") {
      plate_number = plate_number.slice(0, 7);
    }
    
    // 添加
    if (!member[0].id) {
      console.log(member[0].plate_number);
      // 提示
      try {
        // 提示
        await ApiMemberCarAdd(plate_number);
        // openToast("success", "添加" + plate_number + "成功");
        // SetShowToast(true);
        // 提示
        openToast("success", "添加" + plate_number + "成功");
        SetShowToast(true);

        // 更新
        dispatch(
          changeUser({
            ...user,
            member_car_plate_number: plate_number,
          })
        );
        //  重新请求
        ApiMemberCarList().then((res) => {
          const data = res.data.filter((item) => item.status == 1)[0];
          // console.log(data);
          setMember([{ ...data, plate_number: plate_number }]);
          dispatch(changeCarList([{ ...data, plate_number: plate_number }]));
        });

        // navigate("/home", { replace: true });
        setTimeout(() => {
          Taro.reLaunch({
            url: "/pages/home/index",
          });
        }, 1000);
      } catch (error: any) {
        // Toast.show({
        //   content: error.msg,
        // });
        // 车牌号 xxxxxx已被其它会员绑定使用，如有疑问请致电020-3288 8888
        Toast.show("test", {
          title: error.msg,
          duration: 2,
          type: "fail",
        });
      }
      return;
    }

    // 是否保存？
    //  const plate_number = isInput? member[0]
    //    ? member[0].plate_number
    //    : member[0].plate_number

    // 修改
    Dialog.open("dialog", {
      content: "是否保存车牌号" + plate_number,
      // content: (
      //     <View>是否保存车牌号{member[0].plate_number}</View>
      // ),
      // 确认修改
      onConfirm: () => {
        Dialog.close("dialog");
        ApiMemberCarUpdate({
          member_car_id: member[0].id!,
          plate_number: plate_number!,
        })
          .then((res) => {
            if (res.code != 0) {
              Toast.show("test", {
                title: res.msg,
                duration: 6,
                type: "fail",
              });
              setTipTxt(true)
              return;
            }
            // 更新
            // dispatch(changeCarList(member));
            //  重新请求
            ApiMemberCarList().then((res) => {
              const data = res.data.filter((item) => item.status == 1)[0];
              // console.log(data);
              setMember([{ ...data, plate_number: plate_number }]);
              dispatch(
                changeCarList([{ ...data, plate_number: plate_number }])
              );
            });
            // 更新
            dispatch(
              changeUser({
                ...user,
                member_car_plate_number: plate_number,
              })
            );
            dispatch(
              changeUser({
                ...user,
                member_car_plate_number: plate_number,
              })
            );
            // 提示
            openToast("success", "更新" + plate_number + "成功");
            SetShowToast(true);
            // Taro.showToast({
            //   title: "更新" + member[0].plate_number + "成功",
            //   icon: "success",
            //   duration: 2000,
            // });
            setTimeout(() => {
              Taro.reLaunch({
                url: "/pages/home/index",
              });
            }, 1000);
            // await mapMemberCarList();
          })
          .catch((error) => {
            Toast.show("test", {
              title: error.msg,
              duration: 4,
              type: "fail",
            });
            setTipTxt(true)
            return;
          });
      },
      onCancel: () => {
        Dialog.close("dialog");
        Toast.show("success", {
          title: "已取消更新",
          duration: 2,
        });
      },
    });
  };

  // 车辆详情 二次处理数据
  const mapMemberCarList = async () => {
    let data: Datum;
    // console.log(memberCarList, "memberCarList");
    if (memberCarList.length != 0) {
      setLoading(false);
      data = memberCarList.filter((item) => item.status == 1)[0];
      console.log(data, "1");
      setMember([{ ...data, plate_number: "" }]);
      setMemberVal(data.plate_number!);
      setCreateTime(data.created_at!);
      setUpdateTime(data.updated_at!);
    } else {
      const res = await ApiMemberCarList();
      setLoading(false);
      // 存起来
      dispatch(changeCarList(res.data));
      data = res.data.filter((item) => item.status == 1)[0];
      console.log(data, "2");
      setMember([{ ...data, plate_number: "" }]);
      setMemberVal(data?.plate_number!);
      setCreateTime(data?.created_at!);
      setUpdateTime(data?.updated_at!);
    }
    console.log(member);
  };

  // 车辆详情
  const getMemberCarList = async () => {
    // 请求车辆列表
    try {
      // 二次处理
      await mapMemberCarList();
    } finally {
      // 无论请求成功或失败，都设置 loading 为 false
      // 使用骨架屏
      // setLoading(false);
    }
  };

  // 切换为两地车牌
  const changeInput = () => {
    setMember([{ ...member[0], plate_number: member[0].plate_number?.replace(/-/g, "") }]);
    setIsInput(true);
    setShowKeyboard(false);
    setVisibleTip(false);
  };
  // 切换为特殊车牌
  const changeInput2 = () => {
    console.log(visibleTip, "visibleTip");
    setMember([
      { ...member[0], plate_number: member[0].plate_number?.padEnd(7, '-') },
    ]);
    setIsInput(false);
    setShowKeyboard(true);
  };

  // 在组件中添加 ref
  const timerRef = useRef<number | null>(null);
  

  // 检查登录 获取member_id
  // const initData = async () => {
    // 请求用户信息
    // const member_id = await checkLogin();
    // if (!member_id) return;
    // 用于后续 获取会员详情信息
    // await getMemberInfo(member_id);
    // 请求车辆列表
    // getMemberCarList();
  // };

  // 挂载页面
  useEffect(() => {
    // 检查登录 获取member_id
    // initData();
    getMemberCarList();
  }, []);

  // 设置默认值+监听
  useEffect(() => {
    // 更新高亮
    const length = member[0]?.plate_number?.length;
    // console.log(length, "length");
    setCurrentInput(length || 0);

    // if (length == 8) {
    //   setCurrentInput(8);
    // } else {
    //   setCurrentInput(length || 0);
    // }
    if (length == 7 || length == 8) {
      setNewEnergy(true);
    } else {
      setNewEnergy(false);
    }
  }, [member[0]?.plate_number?.length]);

  // 设置默认值+监听
  useEffect(() => {
    // 更新表单
    form.setFieldsValue(member[0]);
  }, [member]);
  const darkTheme = {
    // nutuiColorPrimary: "#1677ff",
    // nutButtonPrimary: "#1677ff",
    nutuiColorPrimaryStop1: "#1677ff",
    nutuiColorPrimaryStop2: "#1677ff",
  };

  return (
    <View>
      <ConfigProvider theme={darkTheme}>
        <Dialog id="dialog" />
      </ConfigProvider>
      <Toast id="test" />
      <Toast
        msg={state.msg}
        visible={showToast}
        type={state.type}
        onClose={() => {
          SetShowToast(false);
        }}
        // cover={state.cover}
      />
      <View style={{ display: loading ? "" : "none" }}>
        <View className="logo">
          <View className="box">
            {
              <>
                {/* 隐藏 */}
                <ConfigProvider
                  theme={{
                    nutuiLoadingIconSize: "16vw",
                    nutuiLoadingIconColor: "#37aae1",
                  }}
                  className="loading"
                >
                  <Loading></Loading>
                  {/* <Loading>加载中</Loading> */}
                </ConfigProvider>
              </>
            }
          </View>
        </View>
      </View>
      <View style={{ display: loading ? "none" : "" }}>
        <View className="title" style={{ display: memberVal ? "" : "none" }}>
          当前车牌号
        </View>
        <Form
          style={{ display: memberVal ? "" : "none" }}
          // initialValues={{ memberVal, createTime, updateTime }}
          divider
          // layout="horizontal"
          labelPosition="left"
          form={form}
        >
          {/* <Form.Header>{memberVal ? "当前车牌号" : ""}</Form.Header> */}
          <Form.Item
            label=""
            style={{
              height: "2vh",
              margin: "0",
              padding: "0",
              display: memberVal ? "" : "none",
            }}
          >
            <></>
          </Form.Item>
          <Form.Item
            name="plate_number"
            label="当前车牌号"
            style={{
              display: memberVal ? "" : "none",
              // borderBottom: "1px solid #ccc",
            }}
          >
            <>
              <Input
                value={memberVal}
                placeholder="当前车牌号"
                // onChange={(val) => changeMember(val)}
                disabled
              />
            </>
          </Form.Item>
          <Form.Item
            label="创建时间"
            style={{
              display: member[0]?.id ? "" : "none",
            }}
          >
            <>
              <Input
                value={createTime}
                placeholder={dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss")}
                disabled
              />
            </>
          </Form.Item>
          <Form.Item
            label="更新时间"
            style={{
              display: member[0]?.id ? "" : "none",
              // borderBottom: "1px solid #ccc",
            }}
          >
            <>
              <Input
                style={{}}
                value={updateTime}
                placeholder={dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss")}
                readOnly
              />
            </>
          </Form.Item>
          <Form.Item
            label=""
            style={{
              display: member[0]?.id ? "" : "none",
            }}
          >
            <></>
          </Form.Item>
        </Form>
      </View>
      <View className="title">使用新车牌</View>
      <Form
        style={{
          display: loading ? "none" : "",
          marginTop: "20px",
          position: "relative",
        }}
        divider
        initialValues={{ ...member[0] }}
        labelPosition="left"
        form={form}
        footer={
          <Button
            formType="submit"
            style={{
              backgroundColor:
                member[0].plate_number &&
                member[0].plate_number.length > 6 &&
                !member[0].plate_number.slice(0, 7).includes("-")
                  ? "#1677ff"
                  : "hsl(215, 100%, 84%)",
              border: "hsl(215, 100%, 84%)",
              width: "90vw",
              paddingTop: "3.3vh",
              paddingBottom: "3.3vh",
              fontSize: "4.8vw",
            }}
            block
            color="primary"
            size="large"
            onClick={determine}
          >
            确认
          </Button>
        }
      >
        <Form.Item
          label=""
          style={{
            height: "2vh",
            margin: "0",
            padding: "0",
          }}
        >
          <></>
        </Form.Item>
        {/* <View>{showKeyboard ? "showKeyboard" : "no_showKeyboard"}</View>
          <View>{visibleTip ? "visibleTip" : "no_visibleTip"}</View>
          <View>{isInput ? "isInput" : "no_isInput"}</View> */}
        <View style={{ display: showKeyboard ? "" : "none" }}>
          {/* <View>{member[0].plate_number}</View> */}
          <Keyboard
            onChange={(newValue) => changeMember(newValue)}
            isShow={true}
            setLicense={member[0].plate_number} // 将setLicense函数传递给子组件
            isTxt={isTxt}
          />
        </View>

        <Form.Item
          name="plate_number"
          label="使用新车牌"
          style={{
            display: isInput ? "" : "none",
            // borderBottom: "1px solid #ccc",
          }}
        >
          <Input
            style={{}}
            placeholder="输入新车牌号"
            onChange={(val) => changeMember(val)}
          ></Input>
        </Form.Item>
        <Form.Item
          label=""
          style={{
            display: isInput ? "none" : "",
            height: "2vh",
            margin: "0",
            padding: "0",
          }}
        >
          <span></span>
        </Form.Item>
        <View
          style={{
            display: tipTxt ? "" : "none",
            textAlign: "center",
            color: "#777",
            fontSize: "3vw",
          }}
        >
          如遇到问题,可致电020-3288 8888
        </View>
      </Form>
      <View className="center">
        <View className="tip">
          <View
            style={{
              textAlign: "center",
              fontSize: "4vw",
              padding: "1vh 2vw",
              position: "relative",
            }}
          >
            <View
              id="tip"
              className="popover"
              style={{ display: visibleTip ? "" : "none" }}
            >
              <View>
                <View
                  style={{ display: "inline-block" }}
                  onClick={() => {
                    setVisibleTip(false);
                  }}
                >
                  <View>当前页面仅支持输入粤港、粤澳、大陆车牌,</View>
                  香港或澳门本土车牌，可点击切换特殊车牌
                </View>
                <View
                  style={{
                    marginLeft: "0.7vw",
                    top: "-4.5vw",
                    position: "relative",
                    fontSize: "4vw",
                    display: "inline-block",
                  }}
                >
                  <Close
                    size="4vw"
                    onClick={() => {
                      setVisibleTip(false);
                    }}
                  />
                </View>
              </View>
            </View>
          </View>
          {/* 特殊车牌 切 两地 */}
          <View style={{ display: isInput ? "flex" : "none" }}>
            <span className="margin" onClick={changeInput2}>
              大陆、粤港/澳 两地牌
            </span>
            <ArrowRight size="3.7vw" onClick={changeInput2} />
          </View>
        </View>

        {/* 大陆、粤港/澳 切 特殊*/}
        <View className="tip" style={{ display: isInput ? "none" : "" }}>
          {/* <Ask
            size="4.7vw"
            onClick={() => {
              // 清除上一次的定时器
              clearInterval(timerRef.current as number);
              timerRef.current = window.setTimeout(() => {
                setVisibleTip(false);
              }, 4000);
              setVisibleTip(true);
            }}
          /> */}
          <span className="margin" onClick={changeInput}>
            使用特殊车牌号
          </span>
          <ArrowRight size="3.7vw" onClick={changeInput} />
        </View>
      </View>
      <View
        style={{ display: "inline-block" }}
        onClick={() => {
          setVisibleTip(false);
        }}
      >
        <View
          style={{
            textAlign: "center",
            width: "100vw",
            fontSize: "3vw",
            padding: "1vh 2vw",
            color: "#aaa",
            display: !isInput ? "block" : "none",
          }}
          onClick={changeInput}
        >
          提示: 当前页面仅支持输入粤港、粤澳、大陆车牌,
          <View>香港或澳门本土车牌，可点击切换特殊车牌</View>
        </View>
      </View>
    </View>
  );
};

export default member;
